const express = require('express');
const mongo = require('../dataBase/users');
const router = express.Router();
const bodyParser = require('body-parser');
const jsonParser = bodyParser.json();

router.post('/', jsonParser, (req, res) => {
    let addFriend = req.body.data; //发起者添加的用户信息
    let whichUserId = req.body.userId; //发起者用户ID
    mongo.Users.findOne({ userId: whichUserId }, (err, docu) => {
        if (err) {
            res.send({ status: false });
            return
        }
        console.log('发起者的信息' + docu);
        docu.friendList.push(addFriend);
        mongo.Users.findOneAndUpdate({ userId: whichUserId }, { friendList: docu.friendList }, (err, docu) => {
            if (err) {
                console.log(err);
                return;
            }
            console.log('我方添加成功，接下来开始添加至对方的列表');
            var addAnotherData = { //发起者的内容信息
                    userId: docu.userId,
                    avatarImg: docu.avatarImg,
                    name: docu.name
                }
                //向发起者的对方添加数据内容
            mongo.Users.findOne({ userId: addFriend.userId }, (err, docu) => {
                docu.friendList.push(addAnotherData);
                mongo.Users.findOneAndUpdate({ userId: docu.userId }, { friendList: docu.friendList }, (err, docu) => {
                    if (err) {
                        console.log(err);
                        return;
                    }
                    console.log('对方好友列表添加成功');
                    res.send({ status: true });
                })
            })
        })
    }).catch(err => {
        console.log(err);
        res.send({ status: false });
    })
})

module.exports = router;